package cn.aws360.boot.system.biz.service.impl;

import cn.aws360.boot.system.api.pojo.response.SysUserThirdModel;
import cn.aws360.boot.system.biz.domain.SysUser;
import cn.aws360.boot.system.biz.domain.SysUserThird;
import cn.aws360.boot.system.biz.mapper.SysUserThirdMapper;
import cn.aws360.boot.system.biz.service.SysUserService;
import cn.aws360.boot.system.biz.service.SysUserThirdService;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.model.AuthUser;
import org.springframework.stereotype.Service;

/**
 * @author junnan
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysUserThirdServiceImpl extends ServiceImpl<SysUserThirdMapper, SysUserThird> implements SysUserThirdService {

    private final SysUserService sysUserService;

    @Override
    public SysUserThirdModel saveAuthUser(AuthUser authUser) {
        String uuid = authUser.getUuid();
        SysUserThird userThird = this.getOne(Wrappers.<SysUserThird>lambdaQuery().eq(SysUserThird::getUuid, uuid));
        SysUserThirdModel sysUserThirdModel;
        if (userThird != null) {
            SysUser sysUser = sysUserService.getById(userThird.getId());
            sysUserThirdModel = BeanUtil.copyProperties(sysUser, SysUserThirdModel.class);
            sysUserThirdModel.setUuid(userThird.getUuid());
            return sysUserThirdModel;
        }

        SysUser sysUser = BeanUtil.copyProperties(authUser, SysUser.class);
        sysUser.setPassword(sysUserService.getInitPassword());
        sysUserService.save(sysUser);

        userThird = BeanUtil.copyProperties(authUser, SysUserThird.class);
        userThird.setId(sysUser.getId());
        this.save(userThird);
        sysUserThirdModel = BeanUtil.copyProperties(sysUser, SysUserThirdModel.class);
        sysUserThirdModel.setAdd(true);
        sysUserThirdModel.setUuid(userThird.getUuid());
        return sysUserThirdModel;
    }

}
